package com.thermofisher.dsc.amanda.tracking.service.impl;

import com.thermofisher.dsc.amanda.common.crud.service.AbsBaseService;
import com.thermofisher.dsc.amanda.common.util.SessionUtil;
import com.thermofisher.dsc.amanda.model.constant.ActionEnum;
import com.thermofisher.dsc.amanda.model.dto.tracking.TrackingDto;
import com.thermofisher.dsc.amanda.model.po.tracking.Tracking;
import com.thermofisher.dsc.amanda.tracking.mapper.TrackingMapper;
import com.thermofisher.dsc.amanda.tracking.service.TrackingService;
import java.util.Map;
import org.springframework.stereotype.Service;

/**
 * @author wenjie.yang on 3/29/2019.
 */
@Service
public class TrackingServiceImpl extends
    AbsBaseService<TrackingDto, Tracking, TrackingMapper> implements TrackingService{
  public TrackingServiceImpl(TrackingMapper mapper){
    super(mapper);
  }

  @Override
  public TrackingDto createByAction(Map<String,Object> params){
    TrackingDto trackingDto = initTrackingDto(params);
    TrackingDto insertDto = super.create(trackingDto);
    return insertDto;
  }



  private TrackingDto initTrackingDto(Map<String, Object> params) {
    Long userId = SessionUtil.getUserId();
    Integer action = Integer.valueOf(params.get("action").toString());
    TrackingDto trackingDto = ActionEnum.getByAction(action).getTracking();
    trackingDto.setUserId(userId);
    trackingDto.setInfoCollection(getKeyValue(params));
    if (params.containsKey("quantities")){
      trackingDto.setQuantities(Integer.valueOf(params.get("quantities").toString()));
    }
    return trackingDto;
  }

  private String getKeyValue(Map<String,Object> params){
    StringBuffer sb = new StringBuffer("");
    for (String key:params.keySet()){
      if (!key.equals("selected") && !key.equals("action")){
        sb.append(key+":"+params.get(key).toString()+";");
      }
    }
    return sb.toString();
  }


}
